# -*- coding: utf-8 -*-
from odoo import api, http, SUPERUSER_ID, _,fields
import werkzeug
from urllib import parse
import base64
import time
import json
import logging
import qrcode
import datetime
from io import BytesIO
from PIL import Image,ImageFont,ImageDraw
import traceback
from odoo.http import request
from werkzeug.contrib.sessions import SessionMiddleware,FilesystemSessionStore
_logger = logging.getLogger(__name__)
class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, bytes):
            return str(obj, encoding='utf-8');
        return json.JSONEncoder.default(self, obj)
def download_response(name,byte):
    headers = {"Content-Disposition":"attachment; filename*=UTF-8''"+parse.quote_plus(name),
               "X-Content-Type-Options":"nosniff",
               "Content-Length":len(byte)}
    return werkzeug.wrappers.Response(byte,mimetype='application/octet-stream', headers=headers)

def json_response(rp):
    headers = {"Access-Control-Allow-Origin": "*",
               "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
               "Access-Control-Allow-Methods": "GET, POST,OPTIONS","Cache-Control":"no-cache"}
    return werkzeug.wrappers.Response(json.dumps(rp,cls=MyEncoder,ensure_ascii=False), mimetype='application/json;charset=utf-8',headers=headers)

def json_server_send_response(rp):
    headers = {"Access-Control-Allow-Origin": "*","Cache-Control":"no-cache"}
    return werkzeug.wrappers.Response("data:"+json.dumps(rp,cls=MyEncoder,ensure_ascii=False)+"\n\n", mimetype='text/event-stream',headers=headers)

def json_response_options():
    headers = {"Access-Control-Allow-Origin": "*","Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept","Access-Control-Allow-Methods":"GET, POST,OPTIONS"}
    return werkzeug.wrappers.Response("{}",mimetype='application/json;charset=utf-8',headers=headers)

class OrderApi(http.Controller):

    #获取POS列表
    @http.route('/RmApi/pos/get_store_list', type='http', auth="public", csrf=False, methods=['POST', 'OPTIONS', 'GET'])
    def get_store_list_pos(self, *a, **k):
        if request.httprequest.method == "OPTIONS" or request.httprequest.method == "options":
            return json_response_options()

        list = request.env['pos.config'].sudo().search([])
        store_list = {'store_list': []}
        for l in list:
            result = {}
            result['id'] = l.id
            result['name'] = l.name
            result['image_icon'] = l.image_icon
            result['restaurant_address'] = l.restaurant_address
            result['per_capita_consumption'] = l.per_capita_consumption
            result['score'] = 4.3
            store_list['store_list'].append(result)
        # _logger.info('++++++++++++++name:%s++++++++++++++++',l.name)
        # _logger.info('++++++++++++++json.dumps:%s++++++++++++++++', str(store_list))
        # return json.dumps(goods,ensure_ascii=False)
        _logger.info('++++++++++++++methods:%s++++++++++++++++', str(request.httprequest.method))
        return json_response(store_list)

    @http.route('/RmApi/pos/get_goods_list', type='http', auth="public", csrf=False, methods=['post', 'get'])
    def get_goods_list_pos(self, config_id=''):
        list_category = request.env['pos.category'].sudo().search([('config_id', '=', int(config_id))])
        store = request.env['pos.config'].sudo().search([('id', '=', int(config_id))])
        goods = {'name':store.name,'image_icon':store.image_icon,'goods': []}
        for c in list_category:
            _logger.info('++++++++++++++list_category++++++++++++++++')
            list_foods = request.env['product.template'].sudo().search([('config_id', '=', int(config_id)),('pos_categ_id.id','=', c.id)])
            dict_foods = {'type_accumulation': c.id, 'name': c.name, 'foods': []}
            _logger.info('++++++++++++++list_foods:%s++++++++++++++++', str(list_foods))
            for l in list_foods:
                _logger.info('++++++++++++++l.pos_categ_id.name:%s++++++++++++++++', str(l.pos_categ_id.name))
                result = {}
                result['id'] = l.id
                result['name'] = l.name
                # result['pos_categ_id'] = c.id
                # result['flavour'] = l.flavour
                result['list_price'] = l.list_price
                result['described'] = l.described
                result['image_small'] = l.image_small
                dict_foods['foods'].append(result)
            goods['goods'].append(dict_foods)
        _logger.info('++++++++++++++json.dumps:%s++++++++++++++++', str(goods))
        # return json.dumps(goods,ensure_ascii=False)
        return json_response(goods)

    @http.route('/RmApi/pos/write_order_details', type='http', auth='public', csrf=False, method=['POST', 'GET'])
    def pos_write_order(self, success=True, message='', **kwargs):
        result = ""
        rp = ""
        detail_result = ""
        _logger.info('++++++++++++++order:%s++++++++++++++++', str(kwargs))
        order = request.env['pos.order']
        order_line = request.env['pos.order.line']
        # 拿出订单json字符串
        order_str = kwargs.pop('json')
        # 转成字典
        order_json = json.loads(order_str)
        # 拿出桌号
        # Many2one的字段直接传ID
        table_number = order_json.get('table_number', -1)
        belonged_to_id = order_json.get('belonged_to_id', -1)
        order_details = order_json.get('order_details', "")
        belonged_to_id = int(belonged_to_id)
        _logger.info(
            '+++++++order_details:%s-table_number:%s-belonged_to_id:%s++++++++++++',
            order_details, table_number, belonged_to_id)
        if belonged_to_id == -1:
            rp = {'result': False, 'success': False, 'message': "belonged_to_id error"}
            return json_response(rp)
        if table_number == -1:
            rp = {'result': False, 'success': False, 'message': "table_number error"}
            return json_response(rp)
        if order_details == "":
            rp = {'result': False, 'success': False, 'message': "order_details null"}
        order_create = {}
        try:
            order_create['config_id'] = belonged_to_id
            order_create['table_id'] = table_number
            order_create["user_id"] = request.env['pos.session'].sudo().search([('state', '=', 'opened'), ('config_id', '=', belonged_to_id)], limit=1).user_id.id
            order_create["pricelist_id"] = 1
            order_create["company_id"] = 1
            order_create["pos_user_id"] = order_json.get('pos_user_id', '')
            _logger.info('++++++++++++++pos_user_id:%s++++++++++++++++', str(order_json.get('pos_user_id', '')))
            order_create["session_id"] = request.env['pos.session'].sudo().search([('state', '=', 'opened'), ('config_id', '=', belonged_to_id)], limit=1).id

            result = order.sudo().create(order_create).id
            for detail in order_json["order_details"]:
                _logger.info('++++++++++++++detail:%s++++++++++++++++', str(detail))
                # detail_json = json.loads(detail)
                detail_order = {}
                detail_order["order_id"] = int(result)
                # 数量
                detail_order["qty"] = detail.get('count', -1)
                #菜品

                detail_order["table_number"] = table_number
                product_id = request.env['product.product'].sudo().search([('product_tmpl_id', '=', int(detail.get('one_food_id', -1)))], limit=1).id
                #detail.get('one_food_id', -1)
                _logger.info('++++++++++++++product_id:%s++++++++++++++++', str(product_id))
                detail_order["product_id"] = product_id
                detail_result = order_line.sudo().create(detail_order).id
            # 创建一条订单，返回订单ID
            rp = {'result': result, 'success': success, 'message': message}
        except Exception as e:
            rp = {'result': False, 'success': False, 'message': str(e)}
        _logger.info('++++++++++++++order:%s++++++++++++++++', str(order))
        _logger.info('++++++++++++++result:%s-detail_result:%s++++++++++++++++', str(result), detail_result)
        return json_response(rp)

    @http.route('/RmApi/pos/read_order_details', type='http', auth='public', csrf=False, method=['POST', 'GET'])
    def pos_read_order(self, **kwargs):
        pos_user_id = int(kwargs.get('pos_user_id',0))
        order_ids = request.env['pos.order'].sudo().search([('pos_user_id', '=', pos_user_id),('state','in',('paid','done','invoiced'))])
        order_ids_dict = {'order_ids':[]}
        for order in order_ids:
            order_lines = request.env['pos.order.line'].sudo().search([('order_id', '=', order.id)])
            order_ids_dict['order_ids'].append({"name":order.name,
                                           "date_order":order.date_order,
                                            "amount_total":order.amount_total,
                                           "table_id":order.table_id.name,
                                           'order_line': []})
            for order_line in order_lines:
                order_ids_dict['order_ids'][-1]['order_line'].append({"product_id":order_line.product_id.name,
                                                                      "qty":order_line.qty,
                                                                      "price_unit":order_line.price_unit})
        return json_response(order_ids_dict)

    @http.route('/RmApi/pos/get_order_details', type='http', auth="public", csrf=False, methods=['post', 'get'])
    def get_order_details_pos(self, belonged_to_id=0, cooking_state=0):
        list = ""
        # _logger.info('+++++++++++state:%s++++++++++++++++', int(state))
        if int(cooking_state) == 1:
            list = request.env['pos.order.line'].sudo().search(
                [('order_id.session_id.config_id', '=', int(belonged_to_id)), ('cooking_state', 'in', (1, 2)),('product_id.product_tmpl_id.available_in_kitchen','=',True)])
            _logger.info('+++++++++-0-state:%s++++++++++++++++', str(list))
        else:
            list = request.env['pos.order.line'].sudo().search(
                [('order_id.session_id.config_id', '=', int(belonged_to_id)), ('cooking_state', '=', cooking_state),('product_id.product_tmpl_id.available_in_kitchen','=',True)])
            _logger.info('+++++++++-1-state:%s++++++++++++++++', str(list))
        # list = request.env['order.details'].sudo().search([])

        foods = {'foods': []}
        for l in list:
            result = {}
            result['id'] = l.id
            result['table_number'] = l.table_number.name
            result['food_name'] = l.product_id.product_tmpl_id.name
            result['cooking_state'] = l.cooking_state
            result['number'] = l.qty
            result['cooking_time'] = l.cooking_time
            foods['foods'].append(result)
            # _logger.info('++++++++++++++name:%s++++++++++++++++', l.belonged_to_id)
            # _logger.info('++++++++++++++json.dumps:%s++++++++++++++++', str(foods))
        # return json.dumps(goods,ensure_ascii=False)
        return json_server_send_response(foods)

    @http.route('/RmApi/pos/set_order_details_state', type='http', auth="public", csrf=False, methods=['post', 'get'])
    def set_order_details_pos(self, **kwargs):
        # cooking_time=0, id='', state=''
        _logger.info('++++++++++++++belonged_to_id:%s++++++++++++++++', str(kwargs))
        _logger.info('++++++++++++++belonged_to_id:%s++++++++++++++++', str(kwargs.get('id')))
        list = request.env['pos.order.line'].sudo().search([('id', '=', kwargs.get('id'))])
        # list = request.env['order.details'].sudo().search([])
        _logger.info('++++++++++++++list:%s++++++++++++++++', str(list))
        if kwargs.get('cooking_time') != None:
            if list.cooking_time == 0:
                if int(kwargs.get('cooking_time')) != 0:
                    list.write({'cooking_time': int(kwargs.get('cooking_time'))})
                else:
                    return json_response({"isok": "false", "msg": "设置烹饪时间错误"})
            else:
                return json_response({"isok": "false", "msg": "设置烹饪已经设置"})
        if int(kwargs.get('cooking_state')) <= 4:
            if list.cooking_state == 1 or list.cooking_state == 2:
                if int(kwargs.get('cooking_state')) == 2:
                    list.write({'cooking_state': int(kwargs.get('cooking_state')), 'order_taking_time': fields.datetime.now()})
                elif int(kwargs.get('cooking_state')) == 3:
                    list.write({'cooking_state': int(kwargs.get('cooking_state')), 'order_finish_time': fields.datetime.now()})
                elif int(kwargs.get('cooking_state')) == 4:
                    list.write({'cooking_state': int(kwargs.get('cooking_state')), 'order_back_time': fields.datetime.now()})
            else:
                return json_response({"isok": "false", "msg": "状态不允许修改!"})
        else:
            return json_response({"isok": "false", "msg": "状态错误!"})
        # return json.dumps(goods,ensure_ascii=False)
        return json_response({"isok": "true"})

    @http.route('/RmApi/pos/get_order_details_time', type='http', auth="public", csrf=False, methods=['POST','OPTIONS', 'GET'])
    def get_order_details_time_pos(self, belonged_to_id='' , table_number_id='', **kw):
        if request.httprequest.method=="OPTIONS" or request.httprequest.method=="options":
            return json_response_options()
        list = request.env['pos.order.line'].sudo().search([('c_show_active','=',True)])
        _logger.info('++++++++++++++json.dumps:%s++++++++++++++++', str(list))
        food_time = {'food_time':[]}
        for l in list:
            _logger.info('++++++++++++++l.table_number.id:%s++++++++++++++++', str(l.table_number.id))
            _logger.info('++++++++++++++l.belonged_to.id :%s++++++++++++++++', str(l.order_id.config_id.id ))
            if l.table_number.id==int(table_number_id) and l.order_id.config_id.id == int(belonged_to_id):
                food_info={}
                #店家名字
                food_info['name']=l.name
                food_info['table_number'] = l.table_number.name
                food_info['food_name'] = l.product_id.product_tmpl_id.name
                #qty数量
                food_info['number'] = l.qty
                food_info['price_unit'] = l.price_unit
                try:
                    food_info['order_taking_time'] = (datetime.datetime.strptime(l.order_taking_time,'%Y-%m-%d %H:%M:%S')+datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
                except:
                    traceback.print_exc()
                    food_info['order_taking_time'] =l.order_taking_time
                food_info['cooking_time'] = l.cooking_time
                food_info['time_of_completing_to_order'] = (datetime.datetime.strptime(l.order_id.date_order,'%Y-%m-%d %H:%M:%S')+datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
                food_info['cooking_state'] = l.cooking_state
                food_info['config_id'] = l.order_id.config_id.name
                food_time['food_time'].append(food_info)
                _logger.info('++++++++++++++ type(l.order_taking_time):%s++++++++++++++++',  l.order_taking_time)
                _logger.info('++++++++++++++ type(l.order_id.date_order):%s++++++++++++++++', l.order_id.date_order)
            _logger.info('++++++++++++++json.dumps:%s++++++++++++++++', str(l.order_id))
            _logger.info('++++++++++++++belonged_to:%s++++++++++++++++', str(food_time))
        # return json.dumps(goods,ensure_ascii=False)
        return json_response(food_time)

    @http.route('/RmApi/pos/line_up', type='http', auth="public", csrf=False, methods=['post', 'get'])
    def line_up(self,**kwargs):
        config_id = int(kwargs.get('config_id',0))
        _logger.info('++++++++++++++type():%s++++++++++++++++', str(type(config_id)))
        queue = int(kwargs.get('queue',0))
        imei = kwargs.get('imei','')
        pos_user_id = int(kwargs.get('pos_user_id', 0))
        if imei !='' or pos_user_id !=0:
            if queue == 0:
                line_up_id = request.env['line.up'].sudo().search(
                    ['|', ('imei', '=', imei), ('pos_user_id', '=', pos_user_id)], limit=1)
                index = -1
                name = ''
                if len(line_up_id) == 1:
                    for line_id in line_up_id:
                        store = request.env['pos.config'].sudo().search([('id', '=', line_id.config_id.id)])
                        line_up_ids = request.env['line.up'].sudo().search([('config_id', '=', line_id.config_id.id)])
                        for line in line_up_ids:
                            name = line.name
                            index = index + 1
                            if line.imei == imei or line.pos_user_id.id == pos_user_id:
                                return json_response(
                                    {'config_id': line_id.config_id.id, 'imei': imei, 'index': index, 'name': name,
                                     'image_icon': store.image_icon, 'store_name': store.name,
                                     'number': len(line_up_ids)})

                store = request.env['pos.config'].sudo().search([('id', '=', config_id)])
                line_up_ids = request.env['line.up'].sudo().search([('config_id', '=', config_id)])
                return json_response(
                    {'config_id': config_id, 'imei': imei, 'index': index, 'name': name,
                     'image_icon': store.image_icon, 'store_name': store.name, 'number': len(line_up_ids)})
            elif queue == 2:
                line_up_id = request.env['line.up'].sudo().search(
                    ['|', ('imei', '=', imei), ('pos_user_id', '=', pos_user_id)], limit=1)
                index = -1
                name = ''
                if len(line_up_id) == 1:
                    for line_id in line_up_id:
                        store = request.env['pos.config'].sudo().search([('id', '=', line_id.config_id.id)])
                        line_up_ids = request.env['line.up'].sudo().search([('config_id', '=', line_id.config_id.id)])
                        for line in line_up_ids:
                            name = line.name
                            index = index + 1
                            if line.imei == imei or line.pos_user_id.id == pos_user_id:
                                return json_response(
                                    {'config_id': line_id.config_id.id, 'imei': imei, 'index': index, 'name': name,
                                     'image_icon': "", 'store_name': "",
                                     'number': len(line_up_ids)})

                store = request.env['pos.config'].sudo().search([('id', '=', config_id)])
                line_up_ids = request.env['line.up'].sudo().search([('config_id', '=', config_id)])
                return json_response(
                    {'config_id': config_id, 'imei': imei, 'index': index, 'name': name,
                     'image_icon': store.image_icon, 'store_name': store.name, 'number': len(line_up_ids)})
            elif queue ==1 and config_id !=0:
                line_up_id = request.env['line.up'].sudo().search(
                    ['|', ('imei', '=', imei), ('pos_user_id', '=', pos_user_id)], limit=1)
                if len(line_up_id) == 0:
                    store = request.env['pos.config'].sudo().search([('id', '=', config_id)])
                    name = request.env['line.up'].sudo().create(
                        {'imei': imei, 'config_id': config_id, 'pos_user_id': pos_user_id}).name
                    line_up_ids = request.env['line.up'].sudo().search([('config_id', '=', config_id)])
                    index = -1
                    for line in line_up_ids:
                        index = index + 1
                        if line.imei == imei or line.pos_user_id.id == pos_user_id:
                            break
                    return json_response({'config_id': config_id, 'imei': imei, 'index': index, 'name': name,
                                          'image_icon': store.image_icon, 'store_name': store.name,
                                          'number': len(line_up_ids)})
                else:
                    return json_response({'error': '不能再次排队。'})
        return json_response({'error': '参数错误'})

    @http.route('/RmApi/pos/write_pos_booktable', type='http', auth="public", csrf=False, methods=['post', 'get'])
    def write_pos_booktable(self, **kwargs):
        shou_id = kwargs.get('shou_id','')
        belonged_to_id = kwargs.get('belonged_to_id','')
        name = kwargs.get('name','')
        table_remarks= kwargs.get('table_remarks','')
        table_people = kwargs.get('table_people','')
        table_telephone = kwargs.get('table_telephone','')
        table_time= kwargs.get('table_time','')
        pos_user_id = int(kwargs.get('pos_user_id', 0))

        if shou_id != '' and belonged_to_id != '' and name !='' and table_telephone !='' and pos_user_id !=0 :
            try:
                _logger.info('++++++++++++++datetime.datetime.now().year:%s++++++++++++++++',
                             str(datetime.datetime.now().year))
                _logger.info('++++++++++++++table_time:%s++++++++++++++++', str(table_time))
                time_tup = time.strptime(table_time, "%Y-%m-%d %H:%M:%S")

                if time_tup[0] == datetime.datetime.now().year:
                    pos_booktable = request.env['pos.booktable'].sudo().create(
                        {'shou_id': shou_id,
                         'config_id': belonged_to_id,
                         'pos_user_id': pos_user_id,
                         'name': name,
                         'table_remarks': table_remarks,
                         'table_people': table_people,
                         'table_telephone': table_telephone,
                         'table_time': table_time}).id
                    return json_response({'code': 1, 'id': pos_booktable, 'msg': 'ok'})
                else:
                    return json_response({'code': -1, 'id': '', 'msg': 'time year error!'})
            except Exception as e:
                _logger.info('++++++++++++++Exception:%s++++++++++++++++',str(e))
                return json_response({'code': -1, 'id': '', 'msg': 'time error!'})
        if pos_user_id == 0:
            return json_response({'code': 0, 'id': '', 'msg': '请登陆后在订桌！'})
        if belonged_to_id =='':
            return json_response({'code': -1, 'id': '', 'msg': '必选一个餐厅进行订桌！'})
        if table_telephone =='':
            return json_response({'code': -2, 'id': '', 'msg': '联系方式必填！'})
        return json_response({'code': -3,'id':'','msg':'error'})

    @http.route('/RmApi/pos/read_pos_booktable', type='http', auth="public", csrf=False, methods=['post', 'get'])
    def read_pos_booktable(self, **kwargs):
        shou_id = kwargs.get('shou_id', '')
        pos_user_id = int(kwargs.get('pos_user_id', 0))
        read = {"read_pos_booktable": []}
        if shou_id != '' and pos_user_id !=0:

            pos_booktable_ids = request.env['pos.booktable'].sudo().search([('shou_id','=',shou_id),('pos_user_id.id','=',pos_user_id)])

            for pos_booktable_id in pos_booktable_ids:
                store = request.env['pos.config'].sudo().search([('id', '=', int(pos_booktable_id.config_id.id))])
                ret = {}
                ret['name'] = pos_booktable_id.name
                _logger.info('++++++++++++++pos_booktable_id.name:%s++++++++++++++++', str(pos_booktable_id.name))
                ret['store_name'] = store.name
                ret['store_image_icon'] = store.image_icon
                ret['table_people'] = pos_booktable_id.table_people
                ret['table_time'] = pos_booktable_id.table_time
                ret['table_telephone'] = pos_booktable_id.table_telephone
                ret['table_remarks'] = pos_booktable_id.table_remarks
                ret['table_status'] = pos_booktable_id.table_status
                ret['pos_user_id'] = pos_booktable_id.pos_user_id.name
                read['read_pos_booktable'].append(ret)
        return json_response(read)
    @http.route('/RmApi/pos/download', type='http', auth="public", csrf=False, methods=['post', 'get'])
    def pos_download(self, **kwargs):
        type = kwargs.get('type','user_client')
        if type == 'merchant_client':
            app_byte = request.env['attachment.management'].sudo().search([('file_type', '=', 'merchant_client')] , limit=1)
            return download_response(app_byte.file_name,base64.b64decode(app_byte.file))
        else:
            app_byte = request.env['attachment.management'].sudo().search([('file_type', '=', 'user_client')], limit=1)
            _logger.info('++++++++++++++app_byte.file_name:%s++++++++++++++++', str(app_byte.file_name))
            return download_response(app_byte.file_name, base64.b64decode(app_byte.file))
        return json_response("error")

    @http.route('/RmApi/pos/reg', type='http', auth="public", csrf=False, methods=['post', 'get'])
    def pos_user_reg(self, **kwargs):
        name = kwargs.get('name',"")
        username = kwargs.get('username',"")
        password = kwargs.get('password',"")
        imei = kwargs.get('imei',"")
        phone = kwargs.get('phone',"")
        if imei !="" and name !="" and username !="" and password !="":
            try:
                pos_user = request.env['pos.user']
                pos_user_id = pos_user.sudo().create({"name":name,"username":username,"password":password,"imei":imei,"phone":phone})
                return json_response({"code": 1, "msg": "ok","pos_user_id":pos_user_id.id})
            except Exception as e:
                if "username" in str(e):
                    return json_response({"code": -1, "msg": str(e)})
                elif "imei" in str(e):
                    return json_response({"code": -2, "msg": str(e)})
        return json_response({"code":-1,"msg":"args error"})

    @http.route('/RmApi/pos/login', type='http', auth="public", csrf=False, methods=['post', 'get'])
    def pos_user_login(self, **kwargs):
        username = kwargs.get('username',"")
        password = kwargs.get('password',"")
        imei = kwargs.get('imei',"")
        if username != "" and password != "":
            try:
                pos_user_id = request.env['pos.user'].sudo().search([("username",'=',username),("password",'=',password)], limit=1)
                if len(pos_user_id)==1:
                    pos_user_id.write({"imei":imei})
                    return json_response({"code": 1, "msg": "ok", "name": pos_user_id.name, "username": pos_user_id.username, "pos_user_id": pos_user_id.id,"phone": pos_user_id.phone})
                else:
                    return json_response({"code": -2, "msg": "login_error"})
            except Exception as e:
                return json_response({"code": -1, "msg": str(e)})
        if imei != "":
            try:
                pos_user_id = request.env['pos.user'].sudo().search([("imei", '=', imei)], limit=1)
                if len(pos_user_id) == 1:
                    return json_response({"code": 1, "msg": "ok", "name": pos_user_id.name,"username":pos_user_id.username, "pos_user_id": pos_user_id.id,"phone": pos_user_id.phone})
                else:
                    return json_response({"code": -2, "msg": "login_error"})
            except Exception as e:
                return json_response({"code": -1, "msg": str(e)})
        return json_response({"code": -1, "msg": "args error"})

    @http.route('/RmApi/pos/logout', type='http', auth="public", csrf=False, methods=['post', 'get'])
    def pos_user_logout(self, **kwargs):
        pos_user_id = int(kwargs.get('pos_user_id', 0))
        imei = kwargs.get('imei', "")
        if imei != "" and pos_user_id != "":
            try:
                pos_user_id = request.env['pos.user'].sudo().search(
                    [("imei", '=', imei), ("id", '=', pos_user_id)], limit=1)
                pos_user_id.write({"imei":None})
                return json_response({"code": 1, "msg": "logout ok"})
            except Exception as e:
                return json_response({"code": -1, "msg": str(e)})

        return json_response({"code": -1, "msg": "args error"})





